#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-10 下午9:19
# @Author  : Tom
# @Site    : 
# @File    : detail.py
# @Software: PyCharm

import sys
import os

# 加载django配置
# if not os.getenv('DJANGO_SETTINGS_MODULE'):
#     os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mall.settings.dev'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.settings.prod")

sys.path.insert(0, '../')
import django
django.setup()

from django.shortcuts import render
from meiduo_mall.utils.categories import get_categories
from goods.models import SKU
from meiduo_mall.utils.breadcrumb import get_breadcrumb
from django.conf import settings


def generate_static_sku_detail_html(sku_id):
    # 获取sku对象
    sku = SKU.objects.get(id=sku_id)
    # 获取三级广告分类
    categories = get_categories()
    # 获取面包屑
    breadcrumb = get_breadcrumb(sku.category)
    # 获取相应的spu对象
    spu = sku.spu
    # 获取热销排行:上面的视图已经处理完成
    # 创建选项和sku.id的映射关系
    skues = spu.sku_set.order_by('id')
    sku_options = {}
    sku_option = []
    for sku_temp in skues:
        infor_temp = []
        for infor in sku_temp.specs.order_by('spec_id'):
            infor_temp.append(infor.option.id)
            if sku_temp.id == sku.id:
                sku_option.append(infor.option.id)
        sku_options[tuple(infor_temp)] = sku_temp.id
    # 根据产品的规格，选项创建出选项的属性，更改该属性可以再次请求
    specs_list =[]
    specs = spu.specs.order_by('id')
    for index, spec_temp in enumerate(specs):
        option_list = []
        for option in spec_temp.options.order_by('id'):
            option_temp = sku_option[:]
            option_temp[index] = option.id
            option.sku_id = sku_options.get(tuple(option_temp), 0)
            option_list.append(option)
        spec_temp.option_list = option_list
        specs_list.append(spec_temp)

    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
        'spu': spu,
        'sku_id': sku.id,
        'comments': spu.comments,
        'specs_list': specs_list,
    }
    response = render(None, 'detail.html', context)
    return response.content.decode()

if __name__ == '__main__':
    skus = SKU.objects.all()
    for sku in skus:
        sku_str = generate_static_sku_detail_html(sku.id)
        path_str = os.path.join(settings.BASE_DIR, 'static/detail/%d.html' % sku.id)
        with open(path_str, 'w') as file:
            file.write(sku_str)
    print('ok')
